<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { reactive, unref, h, ref } from 'vue'
import { ElMessage, ElTag } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { BaseButton } from '@/components/Button'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { AlertHandle } from '@/api/scada/type'
import SCADAApi from '@/api/scada'
import { Search } from '@/components/Search'
import Process from './components/Process.vue'
import AlertDetail from './components/AlertDetail.vue'
const ids = ref<string[]>([])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await SCADAApi.GetAlertHandleList({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.rows,
      total: res.total
    }
  },
  fetchDelApi: async () => {
    const res = await SCADAApi.DeleteAlertHandle(unref(ids)[0])
    return !!res
  }
})
const { dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    fixed: 'left',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'siteName',
    label: t('名称'),
    // width: 150,
    form: {
      hidden: true
    },
    table: {
      hidden: false
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'vaguePrice',
    label: t('模糊搜索'),
    width: 150,
    form: {
      hidden: true
    },
    table: {
      hidden: true
    },
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '请输入站点名称或编号'
      }
    }
  },
  {
    field: 'devName',
    label: t('设备'),
    // width: 150,
    detail: {
      hidden: false
    },
    table: { hidden: false },
    search: { hidden: true }
  },
  {
    field: 'logTime',
    label: t('上传时间'),
    width: 180,
    form: {
      hidden: true
    },
    detail: {
      span: 24
    },
    search: { hidden: true }
  },
  {
    field: 'alertState',
    label: t('状态'),
    formatter: (_: Recordable, __: any, cellValue: number) => {
      if (cellValue == 0) {
        return h(ElTag, { type: 'info' }, () => t('待处理'))
      } else if (cellValue == 1) {
        return h(ElTag, { type: 'primary' }, () => t('已完成'))
      } else if (cellValue == 2) {
        return h(ElTag, { type: 'danger' }, () => t('未完成'))
      } else if (cellValue == 3) {
        return h(ElTag, { type: 'danger' }, () => t('已超时'))
      }
    },
    form: {
      hidden: true
    },
    detail: {
      span: 24
    },
    search: {
      hidden: false,
      component: 'RadioButton',
      value: '',
      componentProps: {
        options: [
          {
            label: '全部',
            value: ''
          },
          {
            label: '待处理',
            value: 0
          },
          {
            label: '已完成',
            value: 1
          },
          {
            label: '未完成',
            value: 2
          },
          {
            label: '已超时',
            value: 3
          }
        ]
      }
    }
  },
  {
    field: 'value',
    label: t('报警值'),
    form: {
      hidden: true
    },
    detail: {
      span: 24
    },
    search: { hidden: true }
  },
  {
    field: 'limitValue',
    label: t('预警值'),
    form: {
      hidden: true
    },
    detail: {
      span: 24
    },
    search: { hidden: true }
  },
  {
    field: 'alertTypeStr',
    label: t('报警内容'),
    width: 200,
    form: {
      hidden: true
    },
    detail: {
      span: 24
    },
    search: { hidden: true }
  },
  {
    field: 'workUser',
    label: t('处理人'),
    form: {
      hidden: true
    },
    detail: {
      span: 24
    },
    search: { hidden: true }
  },
  {
    field: 'endDate',
    label: t('最晚处理时间'),
    form: {
      hidden: true
    },
    detail: {
      span: 24
    },
    search: { hidden: true }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    fixed: 'right',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: { hidden: true },
    slots: {
      default: (data) => {
        return (
          <>
            {data.row.alertState !== 1 && (
              <span class="TableBtn" onClick={() => action(data.row, 'process')}>
                {t('处理')}
              </span>
            )}
            {data.row.alertState == 1 && (
              <span class="TableBtn" style="color:#909399">
                {t('处理')}
              </span>
            )}
            <span class="TableBtn" onClick={() => action(data.row, 'Detail')}>
              {t('详情')}
            </span>
            <span
              class="TableBtn"
              style="font-weight: 600;color:#f56c6c"
              onClick={() => delData(data.row)}
            >
              {t('删除')}
            </span>
          </>
        )
      }
    }
  }
])
const { allSchemas } = useCrudSchemas(crudSchemas)
const saveLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentRow = ref<any | null>(null)
const ActionType = ref('')
//处理操作
const action = async (row: AlertHandle, type: string) => {
  dialogVisible.value = true
  ActionType.value = type
  currentRow.value = row
  if (type == 'process') {
    dialogTitle.value = '处理'
    currentRow.value = { hanUuid: row.uuid }
  } else {
    dialogTitle.value = '详情'
    const res = await SCADAApi.GetAlertHandleDetails({ hanUuid: row.uuid })
    currentRow.value = res
  }
}
const delLoading = ref(false)
//删除轨迹
const delData = async (row: any) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.dictId] : elTableExpose?.getSelectionRows().map((v: any) => v.dictId) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const writeRef = ref<ComponentRef<typeof Process>>()
const save = async () => {
  dialogVisible.value = false
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    const res: any = ref(false)
    saveLoading.value = true
    res.value = await SCADAApi.AddHandleDetails(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
      ElMessage.success('处理完成!')
    } else {
      ElMessage.error('处理失败!')
    }
  }
}
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      row-key="uuid"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
  <Dialog
    v-model="dialogVisible"
    class="dialog"
    :title="dialogTitle"
    style="width: 40%"
    maxHeight="500px"
  >
    <Process v-if="ActionType == 'process'" ref="writeRef" :current-row="currentRow" />
    <AlertDetail v-else ref="writeRef" :current-row="currentRow" />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('提交') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
    </template>
  </Dialog>
</template>

<style scoped lang="less">
.el-button {
  margin-top: 10px;
}
:deep(.TableBtn) {
  margin: 0 5px;
  font-size: 12px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600 !important;
}
:deep(.el-radio-button--small .el-radio-button__inner) {
  padding: 7px 15px !important;
}
:deep(.el-dialog__body) {
  background: rgb(204, 204, 204, 0.5);
  padding: 10px !important;
}
</style>
